package commRedisStatus

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Number"
	"math"
	"time"
)

func getActiveTime(modelType string, modelName string) int64 {
	consumerData := Consumer.GetValues()

	maxActiveTime := int64(0)
	for _, val := range consumerData {
		if val == nil {
			continue
		}

		value := val.(map[string]interface{})

		mType := value[keyModelType]
		mName := value[keyModelName]
		mTime := value[keyActiveTime]

		if mType != modelType || mName != modelName {
			continue
		}

		// 是否存在该activeTime数据
		if mTime == nil {
			continue
		}
		tm := Number.MakeInt64(mTime)

		// 如果存在，则用来初始化result
		if maxActiveTime == 0 {
			maxActiveTime = tm
		}

		maxActiveTime = int64(math.Max(float64(maxActiveTime), float64(tm)))

	}

	return maxActiveTime

}

func IsActive(modelType string, modelName string, timeout int) bool {
	// 通过时间戳，判断通道服务是否正在运行
	activeTime := getActiveTime(modelType, modelName)
	if activeTime == 0 {
		return false
	}

	now := time.Now().UnixMilli()
	return now-activeTime <= int64(timeout)
}

func GetDataList(timeout int64) []map[string]interface{} {
	return getDataList(timeout, time.Now().UnixMilli())
}

func getDataList(timeout int64, currentTime int64) []map[string]interface{} {
	consumerData := Consumer.GetValues()

	resultList := make([]map[string]interface{}, 0)
	for _, val := range consumerData {
		if val == nil {
			continue
		}
		value := val.(map[string]interface{})

		if timeout == -1 {
			resultList = append(resultList, value)
			continue
		}

		// 剔除失效的任务：超时超到指定范围的业务
		activeTime := Number.MakeInt64(Map.GetOrDefault(value, "activeTime", -1))
		if currentTime-activeTime > timeout {
			continue
		}

		value["currentTime"] = currentTime

		resultList = append(resultList, value)
	}

	return resultList
}
